<?php

namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\CollegeApplicationInterface;

/**
 * @Author:: LuXiang
 * @DateTime: 2017/10/21 3:07
 */
class CollegeApplicationRepository extends Repository implements CollegeApplicationInterface
{
    protected $rules = [
        'created' => [
            'uid' => 'required|integer',
            'school_id' => 'required|integer',
            'school_name'=>'required|min:2|max:32',
            'degree_type'=>'required|min:2|max:32',
            'type'=>'required|integer'
        ]
    ];

    protected $messages = [
        'uid.required'              => "用户 ID 不能为空",
        'uid.integer'               => "用户 ID 必须是整数",
        'school_id.required'        => "学校 ID 不能为空",
        'school_id.integer'         => "学校 ID 必须是整数",
        'school_name.required'      => "学校名称不能为空",
        'school_name.min'           => "学校名称最少两个字",
        'school_name.max'           => "学校名称最多32个字",
        'degree_type.required'      => "学校类型不能为空",
        'degree_type.min'           => "学校类型最少两个字",
        'degree_type.max'           => "学校类型最多32个字",
        'type.required'             => "志愿类型不能为空",
        'type.integer'              => "志愿类型必须是整数",
    ];

    protected function modelName()
    {
        return 'App\Model\CollegeApplication';
    }

    public function fill(array $data)
    {
        $this->validate($data, 'created');
        if ($this->model->where('uid', $data['uid'])
            ->where('school_id', $data['school_id'])
            ->where('school_name', $data['school_name'])->first()) {
            throw new ValidateException('您已填报过该学校');
        }
        if ($this->model->where('uid', $data['uid'])
            ->where('degree_type', $data['degree_type'])
            ->where('sort', $data['sort'])->first()) {
            throw new ValidateException($data['degree_type'] . '第' . $data['sort'] . '志愿重复');
        }

        return $this->save($data);
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();

        $data = $query->leftJoin('school', 'school.id', '=', 'college_application.school_id')
            ->orderBy('uid', 'desc')->simplePaginate($limit, ['college_application.*', 'school.logo'], 'page', $page);
        $list = [];
        foreach ($data as $key => $value) {
            $list[$value->degree_type][] = $value->toArray();
        }

        return $this->simplePaginate('list', $list, $total);
    }

    public function cancel($uid, $id)
    {
        return $this->model->where('id', $id)->update(['status' => 2]);
    }
}